package chooongg.base.manager

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import chooongg.base.utils.NetworkType
import chooongg.base.utils.networkGetType


/**
 * 描述
 * @author: Chooong
 * @date: 2018年08月16日
 * @time: 15:09
 */
object NetworkManager {

    private val networkReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            for (item in networkListeners.iterator()) {
                item.onNetworkChange(networkGetType())
            }
        }
    }

    private val networkListeners = ArrayList<OnNetworkChangeListener>()

    @Suppress("DEPRECATION")
    fun init(context: Context) {
        val intentFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
        context.registerReceiver(networkReceiver, intentFilter)
    }

    fun addNetworkChangeListener(listener: OnNetworkChangeListener) {
        networkListeners.add(listener)
    }

    fun removeNetworkChangeListener(listener: OnNetworkChangeListener) {
        networkListeners.remove(listener)
    }

    interface OnNetworkChangeListener {
        fun onNetworkChange(type: NetworkType)
    }
}